import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import iView from "iview";
import {
  getCookie,
  getCookieObj,
  setCookie,
  canTurnTo,
  openCanTurnTo,
  getSiteConfig
} from "@/libs/util";

Vue.use(Router);

const router = new Router({
  mode: "history"
});

router.customBeforeEach = function(to, from, next, routers, unLoginRouters) {
  const accessToken = getCookie("token");
  const accessRole = getCookieObj("role");
  const siteObj = getSiteConfig();
  const LOGIN_PAGE_NAME = siteObj ? siteObj.login : "index";

  if (!accessToken) {
    //console.log(to.name,unLoginRouters,openCanTurnTo(to.name, unLoginRouters));
    if (openCanTurnTo(to.name, unLoginRouters)) {
      next();
    } else {
      next({
        name: LOGIN_PAGE_NAME
      });
    }
  } else {
    if (accessRole && accessRole !== "undefined") {
      if (openCanTurnTo(to.name, unLoginRouters)) {
        next({
          name: siteObj.type + "-home" //统一到home,然后根据不同角色在跳转到不同的默认页
        });
      } else if (canTurnTo(to.name, accessRole, routers)) {
        next();
      } else {
        next({ replace: true, name: "error_401" });
      }
    } else {
      next({
        name: LOGIN_PAGE_NAME
      });
    }
  }
};

router.customAfterEach = function(to) {
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
};
export default router;
